<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预案名称" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入预案名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['manager:plan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['manager:plan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['manager:plan:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['manager:plan:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <!-- <el-table-column label="关联标签" align="center" prop="planTagList">
        <template slot-scope="scope">
          {{ Association(scope.row) }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="内容" align="center" prop="content" /> -->
      <el-table-column label="预案名称" align="center" prop="planName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="addtoPlan(scope.row)" v-hasPermi="['manager:plan:edit']">添加预案</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['manager:plan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['manager:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改预案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预案名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入预案名称" />
        </el-form-item>
        <el-form-item label="关联标签" prop="planName">
          <el-select v-model="form.planTagList" placeholder="请选择" style="width:100%;" multiple>
            <el-option v-for="item in eventuserList" :key="item.id" :label="item.tagName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  添加预案详细详细 -->
    <el-dialog title="预案信息" :visible.sync="opentow" width="800px" append-to-body>
      <el-form style="flex:1;" :model="formtow" label-width="80px">
        <el-form-item label="预案等级">
          <el-select v-model="formtow.planDetailsId" placeholder="请选择活动区域" style="width:100%;" @change="planchange">
            <el-option v-for="(item, index) in options" :key="index" :label="item.planLeverName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预案内容">
          <el-input type="textarea" v-model="formtow.planContent"></el-input>
        </el-form-item>
      </el-form>

      <template v-for="(item, index) in formtow.planContentList">
        <div style="border-bottom:1px solid #1890ff; padding:10px; display: flex;" :key="index">
          <el-form style="flex:1;" :model="item" label-width="80px">
            <el-form-item label="步骤名称">
              <el-input v-model="item.stepName"></el-input>
            </el-form-item>
            <el-form-item label="步骤介绍">
              <el-input type="textarea" v-model="item.stepIntroduce"></el-input>
            </el-form-item>
            <el-form-item label="">
              <template v-for="(items, indexs) in item.stepDetailsList">
                <div :key="indexs" style="display: flex; margin-bottom: 10px;">
                  <el-form :model="items" label-width="80px" style="flex:1;">
                    <el-form-item label="步骤内容" style="margin-bottom:10px;">
                      <el-input type="textarea" v-model="items.stepDetailsContent"></el-input>
                    </el-form-item>
                    <el-form-item label="步骤人员">
                      <el-cascader clearable style="width:100%;" :props="{ value: 'id', label: 'name', children: 'children', multiple: true, emitPath: false }" v-model="items.personGroupIdListOb" :options="eventTreeList" :show-all-levels="true"></el-cascader>
                    </el-form-item>
                  </el-form>
                  <el-button type="primary" style="height: 34px; margin:0 10px;" v-if="indexs == 0" @click="increaseaddsub(index, indexs)">增加详细步骤</el-button>
                  <el-button type="primary" style="height: 34px; margin:0 10px;" v-if="indexs > 0" @click="deleteaddsub(index, indexs)">删除详细步骤</el-button>
                </div>
              </template>
            </el-form-item>
          </el-form>
          <el-button type="primary" style="height: 34px; margin:0 10px;" v-if="index == 0" @click="increaseadd()">增加步骤</el-button>
          <el-button type="primary" style="height: 34px; margin:0 10px;" v-if="index > 0" @click="deleteadd(index)">删除步骤</el-button>
        </div>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addPlanSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.el-divider--horizontal {
  margin: 10px 0;
  background: #1890ff;
}
</style>
<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan, exportPlan, exPlanGrade, getPlantext, putPlantext, deleteplan, deleteplanlayer, gettagList } from '@/api/event/eventPlan';
import { getuserlist } from '@/api/person/person';
import Editor from '@/components/Editor';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: 'Plan',
  components: {
    Editor,
    Treeselect
  },
  data() {
    return {
      // 事件树表格数据
      eventTreeList: [],
      options: [],
      // 表单参数
      formtow: {
        planDetailsId: '', //预案等级
        planContent: '', //预案处理文件内容
        planContentList: [
          {
            stepName: '',
            stepIntroduce: '',
            stepDetailsList: [
              {
                stepDetailsContent: '',
                personGroupIdListOb: []
              }
            ]
          }
        ]
      },
      eventuserList: [], // 事件组
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预案表格数据
      planList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      opentow: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      stepList: [
        {
          stepName: '', //步骤名称
          details: '', //详情
          actionList: []
        }
      ]
    };
  },
  created() {
    this.getList();
    this.eventlistadd();
  },
  methods: {
    /** 转换事件树数据结构 */
    normalizer(node) {
      console.log(node);
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    removeDomain(item) {
      var index = this.stepList.indexOf(item);
      if (index !== -1) {
        this.stepList.splice(index, 1);
      }
    },
    addDomain() {
      this.stepList.push({
        stepName: '', //步骤名称
        details: '', //详情
        actionList: []
      });
    },
    removeAction(item, b) {
      for (var i = 0; i < this.stepList[b].actionList.length; i++) {
        var index = this.stepList[b].actionList.indexOf(item);
        if (index !== -1) {
          this.stepList[b].actionList.splice(index, 1);
        }
      }
    },
    addAction(num) {
      //    	console.log(num,this.stepList)
      for (var i = 0; i < this.stepList.length; i++) {
        if (i == num) {
          this.stepList[num].actionList.push({
            actionCode: '',
            actionName: ''
          });
        }
      }
      console.log(this.stepList);
    },
    /** 查询预案列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.opentow = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planTagList: [],
        createTime: null,
        planName: null
      };

      this.stepList = [
        {
          stepName: '', //步骤名称
          details: '', //详情
          actionList: []
        }
      ];

      // 表单重置
      this.formtow = {
        planDetailsId: '', //预案等级
        planContent: '', //预案处理文件内容
        planContentList: [
          {
            stepName: '',
            stepIntroduce: '',
            stepDetailsList: [
              {
                stepDetailsContent: '',
                personGroupIdListOb: []
              }
            ]
          }
        ]
      };

      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加预案';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPlan(id).then(response => {
        this.form = response.data;
        this.stepList = response.data.stepList;
        this.open = true;
        this.title = '修改预案';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.stepList = this.stepList;
      console.log(this.form);
      //				return false;
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除预案编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delPlan(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess('删除成功');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有预案数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return exportPlan(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    // 预案等级改变时
    planchange() {
      this.getplanlistadd(this.formtow.planDetailsId);
    },
    // 关联事件
    // Association(data) {
    //   console.log(data);

    //   // for (let [key, val] of Object.entries(this.eventuserList)) {
    //   //   if (val.id == data.planTagList) {
    //   //     return val.eventName;
    //   //   }
    //   // }
    // },
    // 获取预案
    addtoPlan(data) {
      // 打开弹窗
      this.opentow = true;

      // 获取当前预案等级
      exPlanGrade(data.id).then(res => {
        if (res.code == 200) {
          this.options = res.data;
          this.formtow.planDetailsId = res.data[0].id;
          this.getplanlistadd(res.data[0].id);
        }
      });

      // 获取应急组数据
      getuserlist().then(res => {
        console.log(res);
        this.eventTreeList = res.data;
      });
    },
    // 获取预案信息
    getplanlistadd(id) {
      getPlantext(id).then(res => {
        console.log(res);
        if (res.data.planContentList.length != 0) {
          this.formtow = res.data;

          // 修改信息
          for (let key in this.formtow.planContentList) {
            // 循环遍历
            for (let keys in this.formtow.planContentList[key].stepDetailsList) {
              console.log(keys);
              // if (typeof this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb == 'string') {
              //   this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb = this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb.split(',');
              // }
            }
          }

          this.formtow.planDetailsId = res.data.id;
        } else {
          // 重置
          this.formtow.planContent = '';
          this.formtow.planContentList = [
            {
              stepName: '',
              stepIntroduce: '',
              stepDetailsList: [
                {
                  stepDetailsContent: '',
                  personGroupIdListOb: []
                }
              ]
            }
          ];
        }
      });
    },
    // 添加步骤
    increaseadd() {
      this.formtow.planContentList.push({
        stepName: '',
        stepIntroduce: '',
        stepDetailsList: [{}]
      });
    },
    // 删除步骤
    deleteadd(index) {
      // 后台删除
      if (this.formtow.planContentList[index].id) {
        deleteplan(this.formtow.planContentList[index].id).then(res => {
          console.log(res);
        });
      }
      // 页面删除
      this.formtow.planContentList.splice(index, 1);
    },
    // 添加详细步骤
    increaseaddsub(index, indexs) {
      this.formtow.planContentList[index].stepDetailsList.push({
        stepDetailsContent: '',
        personGroupIdListOb: []
      });
    },
    // 删除详细步骤
    deleteaddsub(index, indexs) {
      // 后台删除
      if (this.formtow.planContentList[index].stepDetailsList[indexs].id) {
        deleteplanlayer(this.formtow.planContentList[index].stepDetailsList[indexs].id).then(res => {
          console.log(res);
        });
      }
      // 页面删除
      this.formtow.planContentList[index].stepDetailsList.splice(indexs, 1);
    },
    // 提交预案
    addPlanSubmit() {
      for (let key in this.formtow.planContentList) {
        // 预案等级id
        this.formtow.planContentList[key].planDetailsId = this.formtow.planDetailsId;
        // for (let keys in this.formtow.planContentList[key].stepDetailsList) {
        //   console.log(this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb);
        //   if (typeof this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb == 'object') {
        //     this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb = this.formtow.planContentList[key].stepDetailsList[keys].personGroupIdListOb.join(',');
        //   }
        // }
      }

      console.log(this.formtow);

      // 提交数据后台
      putPlantext(this.formtow).then(res => {
        console.log(res);
        this.opentow = false; // 关闭弹窗
      });
    },
    // 获取事件列表
    eventlistadd() {
      gettagList().then(res => {
        console.log(res);
        this.eventuserList = res.data;
      });
    }
  }
};
</script>
